package com.distribute.domain.utils;

import com.distribute.domain.exception.AuthorizationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


@Aspect
@Component
@Slf4j
public class AppKeyAuthorizationAspect {

    @Value("${project-config.appKey}")
    private String appKey;

    @Before(value = "execution(* com.distribute..*Controller.*(..))")
    public void validatedAppKey() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(attributes)) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String headerAppKey = request.getHeader("token");
        if (!appKey.equals(headerAppKey)) {
            if (StringUtils.isBlank(headerAppKey)) {
                throw new AuthorizationException("Miss credential.");
            }
            throw new AuthorizationException(String.format("The credential is error. %s", appKey));
        }
    }

}
